/*
 * SudokuView.java
 */
package sudoku;

import java.awt.Color;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import javax.swing.JTextField;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;

/**
 * The application's main frame.
 */
public class SudokuView extends FrameView {

    javax.swing.JTextField[][] s = new javax.swing.JTextField[9][9];
    Data data;

    public class Data {

        int[][] fill = new int[9][9];
        int[][] possible = new int[9][9];
        //int[][] tried=new int[9][9];
    }

    public final void initSudoku() {

        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                javax.swing.JTextField s1 = new javax.swing.JTextField(" ");
                s[i][j] = s1;
                s1.setFont(new Font("sansserif", Font.BOLD, 18));
                s1.setHorizontalAlignment(JTextField.CENTER);
                s1.setForeground(Color.BLACK);
                s1.addKeyListener(new java.awt.event.KeyAdapter() {

                    @Override
                    public void keyReleased(java.awt.event.KeyEvent evt) {
                        changed(evt);
                    }
                });
                sudoku.add(s1, new org.netbeans.lib.awtextra.AbsoluteConstraints(j * 40 + j / 3 * 6, i * 40 + i / 3 * 6, 40, 40));
            }
        }
        data = new Data();
    }
    /**
     * This is the method used to solve sudoku.
     * @param i row number. First call should be assigned 0.
     * @param j col number. First call should be assigned 0.
     * @param cells sudoku matrix going to be solved.
     * @return
     */
    private boolean solve(int i, int j, int[][] cells) {
	if (i == 9) {
	    i = 0;
	    if (++j == 9)
		return true;
	}
	if (cells[i][j] != 0)  // skip filled cells
	    return solve(i+1,j,cells);

	for (int val = 1; val <= 9; ++val) {
	    if (statusCheck(i,j,val,cells)) {
		cells[i][j] = val;
		if (solve(i+1,j,cells))
		    return true;
	    }
	}
	cells[i][j] = 0; // reset on backtrack
	return false;
    }
    private boolean statusCheck(int i, int j, int v, int[][] cells) {
//        int v = data.fill[i][j];
        int x, y;
        for (x = i - i % 3; x < i - i % 3 + 3; x++) {
            for (y = j - j % 3; y < j - j % 3 + 3; y++) {
                if (x == i && y == j) {
                    continue;
                }
                if (cells[x][y] == v) {
                    s[x][y].setForeground(Color.red);
                    s[i][j].setForeground(Color.red);
                    return false;
                } else {
                    s[x][y].setForeground(Color.BLACK);
                }
            }
        }
        for (x = 0; x < 9; x++) {
            if (x == i) {
                continue;
            }
            if (cells[x][j] == v) {
                s[x][j].setForeground(Color.red);
                s[i][j].setForeground(Color.red);
                return false;
            } else {
                s[x][j].setForeground(Color.BLACK);
            }
        }
        for (y = 0; y < 9; y++) {
            if (y == j) {
                continue;
            }
            if (cells[i][y] == v) {
                s[i][y].setForeground(Color.red);
                s[i][j].setForeground(Color.red);
                return false;
            } else {
                s[i][y].setForeground(Color.BLACK);
            }
        }
        return true;
    }

    public SudokuView(SingleFrameApplication app) {
        super(app);

        initComponents();
        this.getFrame().setTitle("Sudoku 0.01");
        initSudoku();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        sudoku = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setPreferredSize(new java.awt.Dimension(500, 500));
        mainPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        sudoku.setName("sudoku"); // NOI18N
        sudoku.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        mainPanel.add(sudoku, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 50, 400, 400));

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sudoku.SudokuApp.class).getContext().getResourceMap(SudokuView.class);
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        mainPanel.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 90, -1, -1));

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        mainPanel.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 130, -1, -1));

        setComponent(mainPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        BufferedReader reader= null;
        try{
            try{
               reader = new BufferedReader(new FileReader("input2.txt"));
               StringBuilder sb = new StringBuilder();
               String temp;
               while((temp = reader.readLine())!=null){
               sb = sb.append(temp).append(" ");
               }
               inputarray = sb.toString().split(" +");
               }finally{
               reader.close();
               }
        }catch(IOException e){
            e.printStackTrace();
        }
        data.fill = parseProblem(inputarray);
        for(int i = 0; i < 9; i++){
            for(int j = 0; j < 9; j++){
                if(data.fill[i][j]!=0)
                s[i][j].setText(Integer.toString(data.fill[i][j]));
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        solve(0, 0, data.fill);
        for(int i = 0; i < 9; i++){
            for(int j = 0; j < 9; j++){
                s[i][j].setText(Integer.toString(data.fill[i][j]));
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    void changed(java.awt.event.KeyEvent evt) {
        int i = 0, j = 0;
        javax.swing.JTextField target = (JTextField) evt.getSource();
        for (i = 0; i < 9; i++) {
            for (j = 0; j < 9; j++) {
                if (target == s[i][j]) {
                    break;
                }
            }
            if (j < 9) {
                break;
            }
        }
        char c = evt.getKeyChar();
        if (c <= '9' && c >= '0') {
            target.setText(String.valueOf(c));
            data.fill[i][j] = Integer.parseInt(String.valueOf(c));
            statusCheck(i, j, data.fill[i][j], data.fill);
        } else {
            target.setText("");
        }
    }
//    static int[][] parseProblem(Collection<String> ls) {
//	int[][] problem = new int[9][9]; // default 0 vals
//        for(String str:ls){
//            int i = Integer.parseInt(str.substring(0,1));
//	    int j = Integer.parseInt(str.substring(1,2));
//	    int val = Integer.parseInt(str.substring(2,3));
//	    problem[i][j] = val;
//        }
//	return problem;
//    }
    private int[][] parseProblem(String[] args) {
	int[][] problem = new int[9][9]; // default 0 vals
	for (int n = 0; n < args.length; ++n) {
	    int i = Integer.parseInt(args[n].substring(0,1));
	    int j = Integer.parseInt(args[n].substring(1,2));
	    int val = Integer.parseInt(args[n].substring(2,3));
	    problem[i][j] = val;
	}
	return problem;
    }
    private void writeMatrix(int[][] solution) {
    for (int i = 0; i < 9; ++i) {
        if (i % 3 == 0)
            System.out.println(" -----------------------");
        for (int j = 0; j < 9; ++j) {
            if (j % 3 == 0) System.out.print("| ");
            System.out.print(solution[i][j] == 0
                             ? " "
                             : Integer.toString(solution[i][j]));

            System.out.print(' ');
        }
        System.out.println("|");
    }
    System.out.println(" -----------------------");
    }
    private String[] inputarray;
    private List<String> ls;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JPanel sudoku;
    // End of variables declaration//GEN-END:variables
}
